package com.itheima.health.controller;

import com.itheima.health.entity.Result;
import com.itheima.health.pojo.LoginDto;
import com.itheima.health.pojo.Member;
import com.itheima.health.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Random;

@RestController
public class LoginController {

    @Autowired
    private LoginService loginService;

    @Autowired
    private HttpServletRequest request;

    @PostMapping("/validateCode/send4Login.do")
    public Result validateCode(String telephone){

        Integer code = new Random().nextInt(900000)+100000;
        //模拟发送6位数验证码

        //todo 根据手机号将验证码存储session中
        HttpSession session = request.getSession();
        session.setAttribute(telephone,code+"");
        System.out.println("获取的验证码为:"+code);
        return new Result(true,"模拟验证码存储成功");
    }

    @PostMapping("/member/login.do")
    public Result login(@RequestBody LoginDto loginDto){
        //System.out.println("telephone"+loginDto.getTelephone());
        //System.out.println("code"+loginDto.getValidateCode());
        HttpSession session = request.getSession();
        String code = (String) session.getAttribute(loginDto.getTelephone());
        //System.out.println("获取的验证码为:"+code);
        if(loginDto==null){
            return new Result(false,"所传参数异常");

        }
        if(code==null){
            return new Result(false,"请先获取验证码");
        }
        if(!code.equals(loginDto.getValidateCode())){
            return new Result(false,"验证码不匹配!!!");
        }
        //匹配成功,判断用户是否第一次登录
        Member member = loginService.login(loginDto);
        session.setAttribute("member",member.getId());
        return new Result(true,"登陆成功");
    }

}
